from sqlalchemy import create_engine, Column, Integer, String, Text, DateTime, ForeignKey, Boolean
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
from datetime import datetime, timezone, timedelta
import os
import uuid

# 获取北京时间
def get_beijing_time():
    # 创建UTC时间
    utc_now = datetime.now(timezone.utc)
    # 转换为北京时间（UTC+8）
    beijing_time = utc_now.astimezone(timezone(timedelta(hours=8)))
    return beijing_time

from config import settings

# 创建数据库引擎
engine = create_engine(settings.database_url, connect_args={"check_same_thread": False})

# 创建会话工厂
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# 创建基类
Base = declarative_base()


class User(Base):
    __tablename__ = "users"
    
    id = Column(String(36), primary_key=True, index=True, default=lambda: str(uuid.uuid4()))
    username = Column(String(50), unique=True, index=True, nullable=False)
    email = Column(String(100), unique=False, index=True, nullable=True)
    hashed_password = Column(String(255), nullable=False)
    is_active = Column(Boolean, default=True)
    created_at = Column(DateTime, default=get_beijing_time)
    updated_at = Column(DateTime, default=get_beijing_time, onupdate=get_beijing_time)
    
    # 关系
    sessions = relationship("ChatSession", back_populates="user")
    messages = relationship("ChatMessage", back_populates="user")


class ChatSession(Base):
    __tablename__ = "chat_sessions"
    
    id = Column(String(36), primary_key=True, index=True, default=lambda: str(uuid.uuid4()))
    user_id = Column(String(36), ForeignKey("users.id"), nullable=False)
    title = Column(String(200), default="新会话")
    pinned = Column(Boolean, default=False)  # 是否置顶
    created_at = Column(DateTime, default=get_beijing_time)
    updated_at = Column(DateTime, default=get_beijing_time)  # 移除onupdate参数，避免置顶操作更新日期
    
    # 关系
    user = relationship("User", back_populates="sessions")
    messages = relationship("ChatMessage", back_populates="session")


class ChatMessage(Base):
    __tablename__ = "chat_messages"
    
    id = Column(String(36), primary_key=True, index=True, default=lambda: str(uuid.uuid4()))
    session_id = Column(String(36), ForeignKey("chat_sessions.id"), nullable=False)
    user_id = Column(String(36), ForeignKey("users.id"), nullable=False)
    content = Column(Text, nullable=False)
    message_type = Column(String(20), default="text")  # text, image, audio, file
    file_path = Column(String(500))  # 文件存储路径
    is_user = Column(Boolean, default=True)  # True: 用户消息, False: AI消息
    is_streaming = Column(Boolean, default=False)  # 是否为流式消息（正在生成中）
    is_final = Column(Boolean, default=False)  # 是否为最终消息（流式生成完成）
    created_at = Column(DateTime, default=get_beijing_time)
    
    # 关系
    session = relationship("ChatSession", back_populates="messages")
    user = relationship("User", back_populates="messages")


class UploadedFile(Base):
    __tablename__ = "uploaded_files"
    
    id = Column(String(36), primary_key=True, index=True, default=lambda: str(uuid.uuid4()))
    user_id = Column(String(36), ForeignKey("users.id"), nullable=False)
    filename = Column(String(255), nullable=False)
    file_path = Column(String(500), nullable=False)
    file_size = Column(Integer, nullable=False)
    file_type = Column(String(50), nullable=False)
    uploaded_at = Column(DateTime, default=get_beijing_time)
    
    # 关系
    user = relationship("User")


# 创建数据库表
def create_tables():
    Base.metadata.create_all(bind=engine)


# 获取数据库会话
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()